package com.heima.search.interceptor;

import com.heima.user.pojo.User;
import com.heima.utils.thread.AppUserThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 这里的拦截器主要用于实现搜索的历史记录，将用户登录的userId存进线程中，以便后面获取并作为存进MongoDB的参数之一
 */
public class AppUserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取自媒体用户信息并存到线程中
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)) {
            User user = new User();
            user.setId(Integer.valueOf(userId));
            //存到线程中
            AppUserThreadLocalUtil.setUser(user);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理线程中的数据
        AppUserThreadLocalUtil.clear();
    }
}
